<script>
import { deleteMethodologies, getMethodById } from '@/api/methodology'
import { getDetailInfo } from '@/api/user'
import '@/styles/common.css'

export default {
  name: 'Index',
  data() {
    return {
      // 存储当前工具的所有信息
      dataForm: {
        id: '',
        name: '',
        content: '',
        content_json: '',
        creator_id: '',
        created_at: '',
        updated_at: ''
      },
      // 当前方法创建者的用户名
      userName: '',
      // vuex传递的参数
      isParam: null,
      // 用于三极路由
      isHidden: false
    }
  },
  created() {
    if (this.$router.query === undefined) {
      if (this.$store.getters.methodologyFrom) {
        this.isParam = this.parseQueryString(this.$store.getters.methodologyFrom)
      }
    }
    this.fetchData()
    if (this.$route.path !== '/methodology/index/detail') {
      this.isHidden = true
    }
  },
  methods: {
    // 获取url中携带的参数,赋值给ruleForm
    fetchData() {
      if (this.$route.query.id !== undefined) {
        this.dataForm.id = this.$route.query.id
        this.dataForm.name = this.$route.query.name
        this.dataForm.content = this.$route.query.content
        this.dataForm.content_json = JSON.parse(this.$route.query.content_json)
      }
      // 解决通过面包屑进入详情页没有数据的情况
      if (this.isParam && this.$route.query.id === undefined) {
        const form = this.isParam
        this.dataForm.id = form.id
        this.dataForm.name = form.name
        this.dataForm.content = form.content
        this.dataForm.content_json = JSON.parse(form.content_json)
      }
      getMethodById(this.dataForm.id).then(res => {
        this.dataForm.creator_id = res.creator_id
        this.dataForm.created_at = res.created_at
        this.dataForm.updated_at = res.updated_at
        this.getUserNameById(res.creator_id)
      }).catch(err => {
        console.log('获取方法详情出错：', err)
      })
    },
    // 解析URL中参数的函数
    parseQueryString(queryString) {
      const params = {}
      const pairs = queryString.split('&')
      for (const pair of pairs) {
        const [key, value] = pair.split('=')
        params[key] = value ? decodeURIComponent(value) : ''
      }
      return params
    },
    // 根据创建者id获得创建者的名字
    getUserNameById(id) {
      getDetailInfo(id).then(res => {
        this.userName = res.data.name
      })
    },
    // 将Wed, 28 Aug 2024 19:59:45 GMT字符串，转换为2024-08-28 19:59:45
    stringToDate(dateString) {
      if (typeof dateString !== 'string') {
        // 创建 Date 对象
        const date = new Date(dateString['$date'])

        // 获取年份
        const year = date.getUTCFullYear()
        // 获取月份，注意要加 1，因为月份是从 0 开始的
        const month = String(date.getUTCMonth() + 1).padStart(2, '0')
        // 获取日期
        const day = String(date.getUTCDate()).padStart(2, '0')
        // 获取小时
        const hours = String(date.getUTCHours()).padStart(2, '0')
        // 获取分钟
        const minutes = String(date.getUTCMinutes()).padStart(2, '0')
        // 获取秒
        const seconds = String(date.getUTCSeconds()).padStart(2, '0')

        // 组合成指定格式的字符串
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      // 正则表达式来匹配日期和时间的各个部分
      const regex = /^(\w+),\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d{2}):(\d{2}):(\d{2})\s+GMT$/
      const parts = dateString.match(regex)

      if (!parts) {
        throw new Error('Invalid date string format')
      }

      // 从匹配结果中提取年、月、日等
      const [, , day, monthShort, year, hour, minute, second] = parts

      // 映射月份缩写到数字（注意月份是从0开始的）
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
      const monthIndex = months.indexOf(monthShort)
      if (monthIndex === -1) {
        throw new Error('Invalid month in date string')
      }

      // 创建一个新的Date对象
      const date = new Date(Date.UTC(year, monthIndex, day, hour, minute, second))

      // 格式化日期时间为YYYY-MM-DD HH:MM:SS
      return `${date.getUTCFullYear()}-${(date.getUTCMonth() + 1).toString().padStart(2, '0')}-${date.getUTCDate().toString().padStart(2, '0')} ${date.getUTCHours().toString().padStart(2, '0')}:${date.getUTCMinutes().toString().padStart(2, '0')}:${date.getUTCSeconds().toString().padStart(2, '0')}`
    },
    // 编辑方法
    editMethod() {
      this.$router.push({
        path: '/methodology/index/detail/edit',
        query: {
          id: this.dataForm.id,
          name: this.dataForm.name,
          content: this.dataForm.content,
          content_json: JSON.stringify(this.dataForm.content_json),
        }
      })
    },
    // 删除方法
    deleteMethod() {
      this.$confirm(this.$t('methodology_delete_tips'), this.$t('tip'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        // 删除该Methodology
        deleteMethodologies(this.dataForm.id).then(response => {
          console.log(response.data)
          // 返回方法管理页
          this.$router.push('/methodology/index')
          this.$message({
            message: this.$t('delete_success_tips'),
            type: 'success'
          })
        }).catch(error => {
          console.log(error)
          this.$message({
            message: this.$t('delete_error_tips'),
            type: 'error'
          })
        })
      }).catch(error => {
        console.log(error)
        this.$message({
          message: this.$t('delete_cancel_tips'),
          type: 'info'
        })
      })
    }
  }
}
</script>

<template>
  <div>
    <div :class="{hidden: isHidden}">
      <div class="app-container">
        <!-- 应用的介绍部分 -->
        <el-row class="paragraph_spacing">
          <div class="clearfix">
            <!-- 项目图标 -->
            <div class="left" style="padding-top:15px;width:100px;float:left">
              <img alt="icon" src="@/views/login/img/method.png">
            </div>
            <!-- 项目简介 -->
            <div class="left" style="width:85%;height: fit-content;float:none;margin-left: 120px">
              <!-- 用来调整简介高度的div -->
              <div style="height: 1px;" />
              <p class="large">
                <span style="margin-right: 10px;">{{ dataForm.name }}</span>
              </p>
              <!-- 展示方法的创建者、创建时间、更新时间 -->
              <span class="base">{{ $t('creator')+ ': ' + userName }}</span><br>
              <span class="base">{{ $t('creation_time') + ': ' + stringToDate(dataForm.created_at) }}</span><br>
              <span class="base">{{ $t('update_time') + ': ' + stringToDate(dataForm.updated_at) }}</span><br>
            </div>
          </div>
        </el-row>
        <!-- 数据列表上的按钮行 -->
        <el-row class="clearfix" style="margin-bottom: 10px;">
          <div style="float: left;">
            <span v-if="$store.getters.isAdmin()" style="font-size: 14px;position: relative;top: 17px;">当前共有<span class="font-bold">{{ `${this.dataForm.content_json.length}` }}</span>个子任务</span>
            <span v-else style="font-size: 14px">当前共有<span class="font-bold">{{ `${this.dataForm.content_json.length}` }}</span>个子任务</span>
          </div>
          <div style="float: right">
            <el-button-group>
              <el-button
                v-if="$store.getters.isAdmin()"
                icon="el-icon-edit"
                @click="editMethod"
              > {{ $t('edit') }}
              </el-button>
              <el-button
                v-if="$store.getters.isAdmin()"
                icon="el-icon-delete"
                @click="deleteMethod"
              > {{ $t('delete') }}
              </el-button>
            </el-button-group>
          </div>
        </el-row>
        <!-- 子任务列表 -->
        <el-row>
          <el-table
            loading="listLoading"
            :data="dataForm.content_json"
            :stripe="true"
            element-loading-text="Loading"
            :border="false"
            :header-cell-style="{color:'black'}"
            fit
            highlight-current-row
          >
            <!-- 第一列 序号 -->
            <el-table-column label="序号" align="center" width="119px">
              <template v-slot="scope">
                {{ scope.row.id }}
              </template>
            </el-table-column>
            <!-- 第二列 子任务 -->
            <el-table-column label="子任务" align="center">
              <template v-slot="scope">
                {{ scope.row.task_detail }}
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </div>
    </div>
    <div :class="{hidden: !isHidden}">
      <router-view />
    </div>
  </div>
</template>

<style scoped>
.app-container{
  padding: 20px;
}

.paragraph_spacing{
  margin-bottom: 20px;
}
</style>
